package com.dc.web.admin;

import com.dc.po.User;
import com.dc.service.UserService;
import com.dc.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String loginPage(){
        return "admin/login";
    }

    @GetMapping("/index")
    public String index(){
        return "admin/index";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes){
        User user = userService.checkUser(username, password);
        if(user!=null){
            user.setPassword(null);//抹去密码 保证传输安全
            session.setAttribute("user",user);
            return "redirect:/admin/index";
        }else {
            attributes.addFlashAttribute("msg","用户名或密码错误！");
            return "redirect:/admin";
            // return "admin/login";存在路径问题http://localhost:8080/admin/login;jsessionid=77CA53185E64D9B8BF11B30B063F7CF6
            //使用重定向需使用RedirectAttributes传值，Model只能在一个请求域
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";//使用重定向清除logout
    }


}
